﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.UI.WebControls;
using umbraco.DataLayer;

namespace Designit.Umb.Newsletter.Custom.plugins.designit.newsletter
{
    public partial class editNewsletterCampaign : System.Web.UI.Page
    {
        private int id;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["campaignId"] = "";
                id = int.Parse(Request["id"]);
                Literal1.Text = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<string>("select alias from newsLetterCampaign where id = @id",
                                                                                                  umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id));

                string connectionString = umbraco.BusinessLogic.Application.SqlHelper.ConnectionString;
                string selectSQL = "";
                if (id == 1)
                {
                    selectSQL = "SELECT * FROM newsLetterCampaignNewsletter";
                }
                else if (id == 2)
                {
                    selectSQL = "SELECT * FROM newsLetterCampaignNewsletter where campstatus='draft' or campstatus='delayed'";
                }
                else
                {
                    selectSQL = "SELECT * FROM newsLetterCampaignNewsletter where campstatus='sent'";
                }
                selectSQL += " ORDER BY id DESC";
                SqlConnection con = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand(selectSQL, con);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();

                adapter.Fill(ds);

                Repeater1.DataSource = ds;
                Repeater1.DataBind();

                for (int i = 0; i < Repeater1.Items.Count; i++)
                {

                    Literal lt = (Literal)Repeater1.Items[i].FindControl("LiteralEmail");

                    Button btEdit = (Button)Repeater1.Items[i].FindControl("btnEdit");

                    int mails =
                        umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>("select count (memberId) from newsLetterCampaign2Member where campaignId = @id",
                                                                                       umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", btEdit.CommandArgument));
                    lt.Text = "" + mails;


                    Literal ltStatus = (Literal)Repeater1.Items[i].FindControl("LiteralStatus");
                    if (ltStatus.Text == "sent")
                    {
                        Button btView = (Button)Repeater1.Items[i].FindControl("btnReport");
                        btView.Visible = true;
                        btEdit.Visible = false;
                        Button btDelete = (Button)Repeater1.Items[i].FindControl("btnDelete");
                        btDelete.Visible = false;
                    }


                }

            }

        }



        protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var btnDelete = (Button)e.Item.FindControl("btnDelete");
            var btEdit = (Button)e.Item.FindControl("btnEdit");
            var btCopy = (Button)e.Item.FindControl("btnCopy");
            var btnReport = (Button)e.Item.FindControl("btnReport");

            if (String.Equals(e.CommandName, "Delete"))
            {
                //remove relationship between member and campaign
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsletterCampaign2Member where campaignId=@campaignId",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", btnDelete.CommandArgument));

                //remove relationship between group and campaign
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsLetterCampaign2Group where campaignId=@campaignId",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", btnDelete.CommandArgument));

                //remove campaign
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsletterCampaignNewsletter where id=@campaignId",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", btnDelete.CommandArgument));

                //remove any possible delayed references
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsLetterCampaignDelayedSend where campaignId=@campaignId",
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", btnDelete.CommandArgument));
                id = int.Parse(Request["id"]);
                Response.Redirect("editNewsletterCampaign.aspx?id=" + id);
            }
            else if (String.Equals(e.CommandName, "Edit"))
            {
                Session["campaignId"] = btEdit.CommandArgument;
                Response.Redirect("createNewsletterCampaign.aspx");

            }
            else if (String.Equals(e.CommandName, "Copy"))
            {
                var newId = -1;
                //copy campaign
                using (var reader =
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsletterCampaignNewsletter where id=@id",
                                                                              umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", btCopy.CommandArgument)))
                {
                    while (reader.Read())
                    {
                        newId = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>(
                            "insert into newsletterCampaignNewsletter(camptitle, campsubject, campstatus, campfrom, campreplyMail, campTemplate, campContent, campTemplatecontent, campTrack, campGoogle) values(@title, @subject, @status, @from, @replyMail, @Template, @Content, @campTemplatecontent, @campTrack, @campGoogle); select @@Identity",
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@title",
                                                                                        reader.GetString("camptitle")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@subject",
                                                                                        reader.GetString("campstatus")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@status", "draft"),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@from",
                                                                                        reader.GetString("campfrom")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@replyMail",
                                                                                        reader.GetString("campreplyMail")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Template",
                                                                                        reader.GetString("campTemplate")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content",
                                                                                        reader.GetString("campContent")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campTemplatecontent",
                                                                                        reader.GetString(
                                                                                            "campTemplatecontent")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campTrack",
                                                                                        reader.GetString("campTrack")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campGoogle",
                                                                                        reader.GetString("campGoogle")));

                    }
                }

                //copy campaign2group relationship
                using (var reader =
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsLetterCampaign2Group where campaignId=@id",
                                                                              umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", btCopy.CommandArgument)))
                {
                    while (reader.Read())
                    {
                        umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery(
                            "insert into newsLetterCampaign2Group(campaignId, groupName) values(@id, @name);",
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", newId),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@name",
                                                                                        reader.GetString("groupName")));
                    }
                }

                //copy campaign2member relation
                using (var reader =
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsLetterCampaign2Member where campaignId=@id",
                                                                              umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", btCopy.CommandArgument)))
                {
                    while (reader.Read())
                    {
                        umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery(
                            "insert into newsLetterCampaign2Member(campaignId, memberId) values(@id, @memberId);",
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", newId),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@memberId",
                                                                                        reader.GetInt("memberId")));
                    }
                }
                id = int.Parse(Request["id"]);
                Response.Redirect("editNewsletterCampaign.aspx?id=" + id);
            }
            else if (String.Equals(e.CommandName, "View"))
            {

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"<script type=""text/javascript"">");
                sb.AppendLine("top.openModal('plugins/designit/newsletter/report.aspx?id=" + btEdit.CommandArgument + "', 'View report', 500,608);");
                sb.AppendLine("</script>");
                Page.ClientScript.RegisterStartupScript(this.GetType(), "viewReport", sb.ToString());
            }
        }
    }
}